package com.chaoxin.lovehelp.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chaoxin.lovehelp.common.enums.ErrorCode;
import com.chaoxin.lovehelp.common.enums.SystemEnum;
import com.chaoxin.lovehelp.common.exception.BusinessException;
import com.chaoxin.lovehelp.entity.*;
import com.chaoxin.lovehelp.service.*;
import com.chaoxin.lovehelp.common.enums.vo.*;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.policy.HackLoopTableRenderPolicy;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chaoxin.lovehelp.common.utils.PageUtils;
import com.chaoxin.lovehelp.dao.ActivityDao;

import javax.servlet.http.HttpServletRequest;

@Service("activityService")
public class ActivityServiceImpl extends ServiceImpl<ActivityDao, ActivityEntity> implements ActivityService {

    @Autowired
    private FellowService fellowService;
    @Autowired
    private ActivityRecordService activityRecordService;
    @Autowired
    private RecipientService recipientService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private NeedService needService;

    public List<allActivityVo> getAllActivityList(Map<String, Object> params) throws ParseException {
        //筛选条件
        String start = (String) params.get("startTime");
        String end = (String) params.get("endTime");
        String key = (String) params.get("key");
        QueryWrapper<ActivityEntity> wrapper = new QueryWrapper<>();

        wrapper.eq("is_display",1);
        //根据活动名称筛选
        if(!StringUtils.isEmpty(key)){
            wrapper.like("name",key);
        }
        List<ActivityEntity> activitys = this.list(wrapper);
        List<allActivityVo> vos = new ArrayList<>();
        SimpleDateFormat sdf  = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        if(activitys!=null){
            vos = activitys.stream().map(item->{
                allActivityVo vo = new allActivityVo();
                Integer[] recientIds = activityRecordService.getRecientIds(item.getId());
                if (recientIds.length>0){
                    vo.setButtonType(1);
                }else vo.setButtonType(0);
                BeanUtils.copyProperties(item,vo);
                FellowEntity fellow = fellowService.getById(vo.getResFellowId());
                vo.setFellowName(fellow.getName());
                vo.setFellowTel(fellow.getTel());

                //将开始时间与结束时间转换为时间段
                long l = vo.getEndTime().getTime()-vo.getStartTime().getTime();
                long sumMinute = l / (1000*60);
                long hour = sumMinute/60;
                long minute = sumMinute%60;
                vo.setDuringTime(hour+"小时"+minute+"分");
                sumMinute*=vo.getPeopleNum();
                vo.setAllTime(sumMinute/60+"小时"+sumMinute%60+"分");

                return vo;
            }).collect(Collectors.toList());
        }

        //根据开始时间筛选
        if(!StringUtils.isEmpty(start)){
            Date startTime = sdf.parse(start) ;
            vos = vos.stream().filter(vo->!vo.getEndTime().before(startTime)).collect(Collectors.toList());
        }
        //根据结束时间筛选
        if(!StringUtils.isEmpty(end)){
            Date endTime = sdf.parse(end);
            vos = vos.stream().filter(vo->!vo.getStartTime().after(endTime)).collect(Collectors.toList());
        }
        return vos;
    }
    @Override
    public PageUtils queryPage(Map<String, Object> params) throws ParseException {

        List<allActivityVo> vos = getAllActivityList(params);
        //分页处理
        Integer pageIndex = Integer.parseInt(params.get("page").toString());
        Integer limit = Integer.parseInt(params.get("limit").toString());
        int from = (pageIndex - 1) * limit;
        int to = from + limit > vos.size() ? vos.size() : from + limit;
        List<allActivityVo> vos1 = new ArrayList<>(vos.subList(from, to));
        IPage<allActivityVo> page = new Page<>(pageIndex, limit);
        page.setRecords(vos1);
        page.setTotal(vos.size());
        page.setPages(vos.size() % limit > 0 ? vos.size() / limit + 1 : vos.size() / limit);
        return new PageUtils(page);
    }

    @Override
    public void removeIds(List<Integer> list) {
        if(list!=null){
            for (Integer id:list) {
                ActivityEntity activity = this.baseMapper.selectById(id);
                activity.setIsDisplay(0);
                this.baseMapper.updateById(activity);
                activityRecordService.removeByActivityId(id);
            }
        }

    }

    @Override
    public void saveVo(activityEditVo vo) {
        ActivityEntity activity = new ActivityEntity();
        BeanUtils.copyProperties(vo,activity);
        activity.setIsDisplay(1);
        String fellowIds = Arrays.stream(vo.getFellowIds())
                .map(Object::toString) // 将Integer对象转换为字符串
                .collect(Collectors.joining(","));
        activity.setFellowIds(fellowIds);
        this.save(activity);
        //将受助者id与活动id保存到活动记录中
        for (int i = 0; i < vo.getRecipientIds().length; i++) {
            ActivityRecordEntity record = new ActivityRecordEntity();
            record.setActivityId(activity.getId());
            record.setRecipientId(vo.getRecipientIds()[i]);
            record.setIsDisplay(1);
            activityRecordService.save(record);
        }

    }

    @Override
    public void updateVo(activityEditVo vo) {
        ActivityEntity activity = new ActivityEntity();
        BeanUtils.copyProperties(vo,activity);
        activity.setIsDisplay(1);
        String fellowIds = Arrays.stream(vo.getFellowIds())
                .map(Object::toString) // 将Integer对象转换为字符串
                .collect(Collectors.joining(","));
        activity.setFellowIds(fellowIds);
        this.updateById(activity);
        //活动的受助者可能更改，因此进行识别
        //获取该活动的受助者id
        List<recordRecipientVo> vos = activityRecordService.getRecients(vo.getId());//根据活动id获取（记录号id，受助者id）
        //取出前端传入的受助者id
        List<Integer> newRecipientIds = Arrays.asList(vo.getRecipientIds());
        System.out.println(newRecipientIds);
        for (int i = 0; i < newRecipientIds.size(); i++) {
            for (int j = 0; j < vos.size(); j++) {
                //进行比对，相等的说明为改变，将两边的id改为-1
                if(newRecipientIds.get(i) == vos.get(j).getRecipientId()){
                    vos.get(j).setRecipientId(-1);
                    newRecipientIds.set(i,-1);

                    break;
                }
            }
        }
        //数据库中的受助id不为-1说明前端将其取消，则在记录中删除
        for (int i = 0; i < vos.size(); i++) {
            System.out.println(vos.get(i).getId());
            if(vos.get(i).getRecipientId()!=-1)
                activityRecordService.removeById(vos.get(i).getId());
        }
        //前端传入的受助者id不为-1说明数据库中的记录没有该受助者，进行保存
        for (int i = 0; i < newRecipientIds.size(); i++) {
            if(newRecipientIds.get(i)==-1){
                continue;
            }
            ActivityRecordEntity activityRecord = new ActivityRecordEntity();
            activityRecord.setActivityId(vo.getId());
            activityRecord.setRecipientId(newRecipientIds.get(i));
            activityRecord.setIsDisplay(1);
            System.out.println(activityRecord);
            activityRecordService.save(activityRecord);
        }
    }
    //初始化编辑窗口
    @Override
    public activityEditVo getEditVo(Integer id) {
        ActivityEntity activity = this.getById(id);
        activityEditVo vo = new activityEditVo();
        BeanUtils.copyProperties(activity,vo);
        Integer[] recipients = activityRecordService.getRecientIds(id);
        vo.setRecipientIds(recipients);
        if(!activity.getFellowIds().isEmpty()){
            String[] numbers = activity.getFellowIds().split(",");
            Integer[] fellowIds = new Integer[numbers.length];

            for (int i = 0; i < numbers.length; i++) {
                // 移除可能存在的空格，并转换为int
                fellowIds[i] = Integer.valueOf(numbers[i]);
            }
            vo.setFellowIds(fellowIds);
        }

        return vo;
    }

    //单个活动的受助者信息
    @Override
    public activityRecipientsVo getRecipientsOfActivity(HttpServletRequest request, Map<String, Object> params) {
        //获取登录者
        FellowEntity loginUser = (FellowEntity) request.getSession().getAttribute(SystemEnum.LOGIN_STATUS.getName());
        Integer id = Integer.parseInt(params.get("id").toString());
        String key = (String) params.get("key");
        Boolean isHelpDescriptionComplete = null;
        if (params.containsKey("isHelpDescriptionComplete")) {
            Object value = params.get("isHelpDescriptionComplete");
            if (value instanceof Boolean) {
                isHelpDescriptionComplete = (Boolean) value;
            } else if (value instanceof String && !StringUtils.isEmpty(((String) value))) {
                String strValue = ((String) value).toLowerCase();
                isHelpDescriptionComplete = "true".equals(strValue);
            }
        }

        ActivityEntity activity = this.getById(id);
        activityRecipientsVo vo = new activityRecipientsVo();
        BeanUtils.copyProperties(activity, vo);

        List<recordRecipientVo> recients = activityRecordService.getRecients(id);
        vo.setRecipientNum(recients.size());

        List<activityRecipientVo> activityRecipientVos = new ArrayList<>();

        if (loginUser.getRole() != 1 && loginUser.getRole() != 2) {



        }

        for (int i = 0; i < recients.size(); i++) {
            activityRecipientVo recipentInfo = recipientService.getRecipentInfos(recients.get(i).getRecipientId());
            //如果不是管理员，只选出是属于自己对接的受助者,不是自己的就跳过
            if (loginUser.getRole() != 1 && loginUser.getRole() != 2) {//普通用户
                if (!loginUser.getId().equals(recipentInfo.getFellowId())) {
                        continue;
                }

            }
            ActivityRecordEntity record = activityRecordService.getById(recients.get(i).getId());

            // 设置detail信息
            recipentInfo.setActivityRecordId(recients.get(i).getId());
            recipentInfo.setDetail(record.getDetail());
            recipentInfo.setDetailPic(record.getDetailPic());
            // 名称筛选
            if (!StringUtils.isEmpty(key) && !recipentInfo.getName().contains(key)) {
                continue;
            }

            // 帮助描述筛选
            if (isHelpDescriptionComplete != null) {
                boolean hasDetail = !StringUtils.isEmpty(record.getDetail());
                if (isHelpDescriptionComplete && !hasDetail) {
                    continue;  // 需要非空但为空，跳过
                }
                if (!isHelpDescriptionComplete && hasDetail) {
                    continue;  // 需要空但非空，跳过
                }
            }

            activityRecipientVos.add(recipentInfo);
        }

        vo.setRecipients(activityRecipientVos);
        return vo;
    }
    @Override
    public PageUtils getFellowActivity(HttpServletRequest httpServletRequest, Map<String, Object> params) throws ParseException {
        SimpleDateFormat sdf  = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        List<fellowActivityVo> vos = getFellowActivityList(params);
        //获取登录的用户
        FellowEntity loginUser =(FellowEntity) httpServletRequest.getSession().getAttribute(SystemEnum.LOGIN_STATUS.getName());
        //登录用户不为空
        if(loginUser==null){
            throw  new BusinessException(ErrorCode.NOT_LOGIN_ERROR,"用户未登录");
        }
        //判断登录用户是否为管理员
        if(loginUser.getRole()!=1 && loginUser.getRole()!=2){
            //不是管理员，只能查看自己的志愿活动记录，使用迭代器剔除掉非登录用户的记录
            Iterator<fellowActivityVo> iterator = vos.iterator();
            while (iterator.hasNext()){
                fellowActivityVo vo = iterator.next();
                if(vo.getFellowId()!=loginUser.getId()){
                    iterator.remove();
                }
            }


        }
        //分页处理
        Integer pageIndex = Integer.parseInt(params.get("page").toString());
        Integer limit = Integer.parseInt(params.get("limit").toString());
        int from = (pageIndex - 1) * limit;
        int to = from + limit > vos.size() ? vos.size() : from + limit;
        List<fellowActivityVo> vos1 = new ArrayList<>(vos.subList(from, to));
        IPage<fellowActivityVo> page = new Page<>(pageIndex, limit);
        page.setRecords(vos1);
        page.setTotal(vos.size());
        page.setPages(vos.size() % limit > 0 ? vos.size() / limit + 1 : vos.size() / limit);
        return new PageUtils(page);

    }
    //导出会员活动
    @Override
    public void exportFellowsActivity(Map<String, Object> params) throws ParseException, UnsupportedEncodingException {
        String fileName = (String) params.get("fileName");
        System.out.println(fileName);
        String filePath = System.getProperty("user.home")+ File.separator+"Desktop";
        System.out.println(filePath);
        fileName = filePath+"\\"+fileName+".xlsx";
        SimpleDateFormat sdf  = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        List<fellowActivityVo> vos = getFellowActivityList(params);

        Workbook workbook = new XSSFWorkbook(); // 创建新的Excel工作簿
        Sheet sheet = workbook.createSheet("会员活动记录"); // 创建新的工作表

        // 创建表头
        Row headerRow = sheet.createRow(0);
        Cell headerCell = headerRow.createCell(0);
        headerCell.setCellValue("活动名称");
        headerCell = headerRow.createCell(1);
        headerCell.setCellValue("活动时间");
        headerCell = headerRow.createCell(2);
        headerCell.setCellValue("姓名");
        headerCell = headerRow.createCell(3);
        headerCell.setCellValue("类型");
        headerCell = headerRow.createCell(4);
        headerCell.setCellValue("年龄");
        headerCell = headerRow.createCell(5);
        headerCell.setCellValue("性别");
        headerCell = headerRow.createCell(6);
        headerCell.setCellValue("居住地址");
        headerCell = headerRow.createCell(7);
        headerCell.setCellValue("活动时长");
        // 遍历List<Member>并将数据写入工作表
        int rowNum = 1;
        for (fellowActivityVo vo : vos) {
            Row dataRow = sheet.createRow(rowNum++);
            Cell dataCell = dataRow.createCell(0);
            dataCell.setCellValue(vo.getName());
            dataCell = dataRow.createCell(1);
            String date = sdf.format(vo.getStartTime());
            dataCell.setCellValue(date);
            dataCell = dataRow.createCell(2);
            dataCell.setCellValue(vo.getFellowName());
            dataCell = dataRow.createCell(3);
            dataCell.setCellValue(vo.getCategory()==0?"会员":"非会员");
            dataCell = dataRow.createCell(4);
            if(vo.getAge()!=null){
                dataCell.setCellValue(vo.getAge());
            }

            dataCell = dataRow.createCell(5);
            dataCell.setCellValue(vo.getGender()==0?"男":"女");
            dataCell = dataRow.createCell(6);
            dataCell.setCellValue(vo.getAddress());
            dataCell = dataRow.createCell(7);
            dataCell.setCellValue(vo.getDuringTime());
        }

        //设置列宽
        sheet.setColumnWidth(0,5000);
        sheet.setColumnWidth(1,5000);
        sheet.setColumnWidth(2,2000);
        sheet.setColumnWidth(3,2000);
        sheet.setColumnWidth(4,2000);
        sheet.setColumnWidth(5,2000);
        sheet.setColumnWidth(6,2500);
        sheet.setColumnWidth(7,3000);
        // 创建文件输出流以写入文件
        try (FileOutputStream outputStream = new FileOutputStream(fileName)) {
            workbook.write(outputStream);
            System.out.println("Excel文件已生成：" + fileName);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭工作簿
            try {
                workbook.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }
    //导出单个活动的受助者信息
    @Override
    public void exportRecipientsActivity(Integer id) throws IOException {
        String filePath = System.getProperty("user.home")+ File.separator+"Desktop";
        SimpleDateFormat sdf  = new SimpleDateFormat("yyyy.MM.dd");
        SimpleDateFormat sdfMM  = new SimpleDateFormat("MM");
        SimpleDateFormat sdfdd  = new SimpleDateFormat("dd");
        ActivityEntity activity = this.getById(id);
        FellowEntity resFellow = fellowService.getById(activity.getResFellowId());
        List<recordRecipientVo> recipients = activityRecordService.getRecients(id);
        List<allRecipientVo> vos = new ArrayList<>();
        for (int i = 0; i < recipients.size(); i++) {
            RecipientEntity item = recipientService.getById(recipients.get(i).getRecipientId());
            allRecipientVo vo = new allRecipientVo();

            if(item.getFellowId()!=null){
                FellowEntity fellow = fellowService.getById(item.getFellowId());

                vo.setFellowName(fellow.getName());
                vo.setFellowTel(fellow.getTel());
            }
            BeanUtils.copyProperties(item,vo);
            CategoryEntity category = categoryService.getById(item.getCategoryId());
            vo.setCategoryName(category.getName());
            vos.add(vo);
        }
        XWPFTemplate template;
        // 1. 加载合同模板文件
        for (int i = 0; i < vos.size(); i++) {
            allRecipientVo vo = vos.get(i);
            List<NeedEntity> needs = getNeedList(vo.getId());
            String need = new String();
            for (int j = 0; j < needs.size(); j++) {
                NeedEntity item = needs.get(j);
                need += sdf.format(item.getEstablishTime())+" "+item.getDetail()+" (第"+item.getEmergencyGrade()+"等级)\n";
            }
            String finalNeed = need;
            if(vo.getCategoryName().equals("爱心来敲门")){
                FileInputStream inputStream = new FileInputStream(new File("爱心来敲门模板.docx"));

                HackLoopTableRenderPolicy policy = new HackLoopTableRenderPolicy();
                Configure config = Configure.newBuilder().bind("detailList", policy).build();

                template = XWPFTemplate.compile(inputStream, config).render(
                        new HashMap<String, Object>() {{
                            put("month",sdfMM.format(activity.getStartTime()));
                            put("date",sdfdd.format(activity.getStartTime()));
                            put("name", vo.getName());
                            put("age", vo.getAge());
                            put("address", vo.getAddress());
                            String sex = new String();
                            if(vo.getGender()!=null){
                                sex = vo.getGender()==0?"男":"女";
                            }
                            put("gender",sex);
                            put("identityId",vo.getIdentityId());
                            put("birthDate",sdf.format(vo.getBirthDate()));
                            put("tel",vo.getTel());
                            put("fellowName",vo.getFellowName());
                            put("fellowTel",vo.getFellowTel());
                            put("townName",vo.getTownName());
                            put("townTel",vo.getTownTel());
                            String nurseName = new String();
                            switch (vo.getNurseGrade()){
                                case 0: nurseName = "全自理";break;

                                case 1:nurseName = "半失能";break;
                                case 2:nurseName = "失能";break;
                                default:nurseName = "正常";break;
                            }
                            put("nurseGrade",nurseName);
                            put("villageName",vo.getVillageName());
                            put("villageTel",vo.getVillageTel());
                            put("isLove",vo.getIsLove()==0?"否":"是");
                            put("isMaterial",vo.getIsMaterial()==0?"否":"是");
                            put("nurseName",vo.getNurseName());
                            put("nurseTel",vo.getNurseTel());
                            put("warmDetail",vo.getWarmDetail());
                            put("coolDetail",vo.getCoolDetail());
                            put("neighborDetail",vo.getNeighborDetail());
                            put("healthyDetail",vo.getHealthyDetail());
                            put("medicationDetail",vo.getMedicationDetail());
                            put("resideDetail",vo.getResideDetail());
                            put("economicSource",vo.getEconomicSource());
                            put("hygieneDetail",vo.getHygieneDetail());
                            put("resFellowName",resFellow.getName());
                            put("resFellowTel", resFellow.getTel());
                            put("need", finalNeed);
                        }}
                );
            }else {
                FileInputStream inputStream = new FileInputStream(new File("每月定期慰问模板.docx"));

                HackLoopTableRenderPolicy policy = new HackLoopTableRenderPolicy();
                Configure config = Configure.newBuilder().bind("detailList", policy).build();
                template = XWPFTemplate.compile(inputStream, config).render(
                        new HashMap<String, Object>() {{
                            put("month",sdfMM.format(activity.getStartTime()));
                            put("date",sdfdd.format(activity.getStartTime()));
                            put("name", vo.getName());
                            put("age", vo.getAge());
                            put("address", vo.getAddress());
                            String sex = new String();
                            if(vo.getGender()!=null){
                                sex = vo.getGender()==0?"男":"女";
                            }
                            put("gender",sex);
                            put("identityId",vo.getIdentityId());
                            put("birthDate",sdf.format(vo.getBirthDate()));
                            put("tel",vo.getTel());
                            put("fellowName",vo.getFellowName());
                            put("fellowTel",vo.getFellowTel());

                            String nurseName = new String();
                            switch (vo.getNurseGrade()){
                                case 0: nurseName = "全自理";break;

                                case 1:nurseName = "半失能";break;
                                case 2:nurseName = "失能";break;
                                default:nurseName = "正常";break;
                            }
                            put("nurseGrade",nurseName);
                            put("villageName",vo.getVillageName());
                            put("villageTel",vo.getVillageTel());
                            put("isLove",vo.getIsLove()==0?"否":"是");
                            put("isMaterial",vo.getIsMaterial()==0?"否":"是");
                            put("nurseName",vo.getNurseName());
                            put("nurseTel",vo.getNurseTel());
                            put("healthyDetail",vo.getHealthyDetail());
                            put("medicationDetail",vo.getMedicationDetail());
                            put("resideDetail",vo.getResideDetail());
                            put("economicSource",vo.getEconomicSource());
                            put("familyDetail",vo.getHygieneDetail());
                            put("resFellowName",resFellow.getName());
                            put("resFellowTel", resFellow.getTel());
                            put("need", finalNeed);
                        }}
                );
            }
            // 4. 导出合同文件
            // 创建文件输出流以写入文件
            File file = new File(filePath,sdf.format(activity.getStartTime())+" "+activity.getName());
            file.mkdir();
            try (FileOutputStream outputStream = new FileOutputStream(filePath+"\\"+sdf.format(activity.getStartTime())+" "+activity.getName()+"\\"+vo.getName()+".docx")) {
                template.write(outputStream);
                System.out.println("Excel文件已生成：" + i);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                // 关闭工作簿
                try {
                    template.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    //获取总志愿时长
    @Override
    public String getAllActivityTime(Map<String, Object> params) throws ParseException {
        List<allActivityVo> vos = getAllActivityList(params);
        long sum = 0;
        for (int i = 0; i < vos.size(); i++) {
            allActivityVo vo = vos.get(i);
            sum += (vo.getEndTime().getTime()-vo.getStartTime().getTime())*vo.getPeopleNum();
        }
        long sumMinute = sum / (1000*60);
        long hour = sumMinute/60;
        long minute = sumMinute%60;
        return hour+"小时"+minute+"分";
    }
    //获取会员活动时长
    @Override
    public String getFellowActivityTime(Map<String, Object> params) throws ParseException {
        List<fellowActivityVo> vos = getFellowActivityList(params);
        long sum = 0;
        for (int i = 0; i < vos.size(); i++) {
            fellowActivityVo vo = vos.get(i);
            ActivityEntity activity = this.getById(vo.getId());
            sum += activity.getEndTime().getTime()-activity.getStartTime().getTime();
        }
        long sumMinute = sum / (1000*60);
        long hour = sumMinute/60;
        long minute = sumMinute%60;
        return hour+"小时"+minute+"分";

    }

    public List<fellowActivityVo> getFellowActivityList(Map<String, Object> params) throws ParseException {
        QueryWrapper<ActivityEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("is_display",1);
        String activityName = (String) params.get("activityName");
        String fellowName = (String) params.get("fellowName");
        String startTime = (String) params.get("startTime");
        String endTime = (String) params.get("endTime");
        String categoryId = (String) params.get("categoryId");
        SimpleDateFormat sdf  = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        if(!StringUtils.isEmpty(activityName)){
            wrapper.like("name",activityName);
        }
        List<ActivityEntity> list = this.list(wrapper);
        List<fellowActivityVo> vos = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {

            ActivityEntity activity = list.get(i);
            if(!StringUtils.isEmpty(startTime)){
                if (activity.getStartTime().before(sdf.parse(startTime)))
                    continue;
            }
            if(!StringUtils.isEmpty(endTime)){
                if (activity.getStartTime().after(sdf.parse(endTime))) {
                    continue;
                }
            }
            long l = activity.getEndTime().getTime()-activity.getStartTime().getTime();
            long sumMinute = l / (1000*60);
            long hour = sumMinute/60;
            long minute = sumMinute%60;

            if(!StringUtils.isEmpty(activity.getFellowIds())){
                String[] numbers = activity.getFellowIds().split(",");
                for (int j = 0; j < numbers.length; j++) {
                    FellowEntity fellow = fellowService.getById(Integer.valueOf(numbers[j]));
                    System.out.println(fellow);
                    if(!StringUtils.isEmpty(fellowName)){
                        if(fellow.getName().indexOf(fellowName)<0){
                            continue;
                        }
                    }
                    if(!StringUtils.isEmpty(categoryId)){
                        if(fellow.getCategory()!=Integer.parseInt(categoryId)){
                            continue;
                        }
                    }
                    fellowActivityVo vo = new fellowActivityVo();
                    BeanUtils.copyProperties(activity,vo);
                    vo.setFellowId(fellow.getId());
                    vo.setFellowName(fellow.getName());
                    vo.setGender(fellow.getGender());
                    vo.setDuringTime(hour+"小时"+minute+"分");
                    vo.setAge(fellow.getAge());
                    vo.setCategory(fellow.getCategory());
                    vo.setTel(fellow.getTel());
                    vo.setAddress(fellow.getAddress());
                    vos.add(vo);
                }
            }
        }
        return  vos;
    }
    public List<NeedEntity> getNeedList(Integer recipientId){
        List<NeedEntity> list = new ArrayList<>();
        QueryWrapper<NeedEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("recipient_id",recipientId).eq("is_display",1).eq("is_slove",0);
        if(wrapper!=null)
            list = needService.list(wrapper);
        return list;
    }

}